# 运行方式：
# python flask_demo1.py --mode cli --singer_mid 0025NhlN2yWrP4
# python flask_demo1.py --mode web
# python flask_demo1.py --help

from flask import Flask, request, jsonify
import requests
import argparse
import sys
import json
import os
base_url=os.getenv("BASE_URL")
app = Flask(__name__)

# 通用函数：获取符合条件的专辑信息
def fetch_albums_by_singer(singer_mid: str, page_no=1, page_size=20):
    url = f"{base_url}/singer/album?singermid={singer_mid}&pageNo={page_no}&pageSize={page_size}"
    response = requests.get(url)

    if response.status_code != 200:
        return []

    data = response.json()
    album_list = data.get("data", {}).get("list", [])

    result = []
    for album in album_list:
        song_count = album.get("latest_song", {}).get("song_count", 0)
        if song_count > 1:
            singers = [
                {
                    "singer_id": s.get("singer_id"),
                    "singer_mid": s.get("singer_mid"),
                    "singer_name": s.get("singer_name")
                }
                for s in album.get("singers", [])
            ]
            result.append({
                "album_mid": album.get("album_mid"),
                "album_name": album.get("album_name"),
                "song_count": song_count,
                "singers": singers
            })

    return result

# Web 接口模式
@app.route("/singer/albums")
def get_singer_albums():
    singer_mid = request.args.get("singer_mid")
    if not singer_mid:
        return jsonify({"error": "缺少 singer_mid 参数"}), 400

    result = fetch_albums_by_singer(singer_mid)
    return jsonify(result)

# 主程序入口
def main():
    parser = argparse.ArgumentParser(description="查询歌手专辑信息")
    parser.add_argument("--mode", choices=["cli", "web"], default="cli", help="运行模式: cli 或 web")
    parser.add_argument("--singer_mid", help="歌手 MID（cli 模式下必填,如：0025NhlN2yWrP4）")
    parser.add_argument("--page_no", type=int, default=1, help="页码")
    parser.add_argument("--page_size", type=int, default=20, help="每页数量")

    args = parser.parse_args()

    if args.mode == "web":
        app.run(debug=True)
    else:
        if not args.singer_mid:
            print("错误：在 CLI 模式下必须提供 --singer_mid 参数")
            sys.exit(1)

        result = fetch_albums_by_singer(args.singer_mid, args.page_no, args.page_size)
        print(json.dumps(result, ensure_ascii=False, indent=2))

if __name__ == "__main__":
    main()